import lib.arithmetics as arithmetics
import lib.problem as problem
import unittest
import math

class Problem024(problem.Problem):
	def __init__(self):
		problem.Problem.__init__(self, 24)
		
		
	def calcPermutation(self, digits, n):
		n -= 1
		repetition = arithmetics.factorial(digits - 1)
		
		availableDigits = list(range(digits))
		permutation = 0
				
		for i in range(digits - 1, -1, -1):
			repetition /= i
			if repetition == 0:
				repetition = 1
			pos = int(n / repetition)
			#pos %= digits
			pos %= len(availableDigits)
			value = availableDigits[pos]
			permutation += int(math.pow(10, i - 1) * value)
			availableDigits.remove(value)
			
		return permutation
			
	def calcAllPerms(self, digits):
		f = arithmetics.factorial(digits)
		for i in range(1, f + 1):
			print self.calcPermutation(digits, i)		
		
		
	
		
	def solve(self):
		return self.calcPermutation(9, 1000000)

	
class Problem024Tester(unittest.TestCase):
	
	def setUp(self):
		self.p024 = Problem024()
		
#	def testValcPermutation3_4(self):
#		perm = self.p024.calcPermutation(3, 4)
#		self.assertEquals(120, perm)
		
		
	def testCalcAllPerms(self):
		self.p024.calcAllPerms(5)
		
#	def testValcPermutation5_100(self):
#		perm = self.p024.calcPermutation(5, 100)
#		self.assertEquals(40231, perm)
#		
#		
#	def testValcPermutation9_million(self):
#		perm = self.p024.calcPermutation(10, 1000000)
#		self.assertEquals(201, perm)
		
		
#	def testSolve(self):
#		self.assertEquals([], self.p024.solve())
